import { login, getCode } from '@/store/action/login'
import { LoginForm } from '@/types/data'
import { Input, NavBar, Form, List, Button, Toast } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory, useLocation } from 'react-router'
import style from './index.module.scss'
export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  const mobileRef = useRef<InputRef>(null)
  const [time, setTime] = useState(0)
  const timeRef = useRef(-1)
  const location = useLocation<{ from: string }>()
  // 登录
  const finish = async (values: LoginForm) => {
    // console.log(values)
    await dispatch(login(values))
    Toast.show({
      icon: 'success',
      content: '登录成功',
      duration: 600,
      afterClose: () => {
        let pathname = location.state ? location.state.from : '/home'
        history.replace(pathname)
      },
    })
  }
  const [form] = Form.useForm()
  // 获取验证码
  const getCodeFn = async () => {
    // 如果定时器开启禁止重复发送验证码
    if (time > 0) {
      return
    }
    // 获取手机号
    const mobile = form.getFieldValue('mobile')
    // 获取校验失败的错误
    const error = form.getFieldError('mobile')
    // console.log(mobile)
    if (!mobile || error.length > 0) {
      // 聚焦
      const mobileDom = mobileRef.current
      mobileDom?.focus()
      return
    }
    await dispatch(getCode(mobile))
    setTime(60)
    timeRef.current = window.setInterval(() => {
      setTime((time) => time - 1)
    }, 1000)
  }
  useEffect(() => {
    if (time === 0) {
      clearInterval(timeRef.current)
    }
  }, [time])
  // 组建销毁时
  useEffect(() => {
    clearInterval(timeRef.current)
  }, [])
  return (
    <div className={style.root}>
      <NavBar onBack={() => history.goBack()}></NavBar>
      <div className="login-form">
        <h2>账号登录</h2>
        <Form
          form={form}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
          }}
          autoComplete="off"
          validateTrigger={['onChange', 'onBlur']}
          onFinish={finish}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              {
                required: true,
                message: '手机号不能为空',
              },
              { pattern: /^1[1-3]\d{9}$/, message: '手机号格式不正确' },
            ]}
          >
            <Input
              maxLength={11}
              ref={mobileRef}
              placeholder="请输入手机号"
            ></Input>
          </Form.Item>

          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra" onClick={getCodeFn}>
                {time === 0 ? '发送验证码' : `${time}s后重新获取`}
              </span>
            }
          >
            <Form.Item
              className="login-item"
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式错误',
                },
              ]}
            >
              <Input maxLength={6} placeholder="请输入验证码"></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button
              type="submit"
              color="primary"
              block
              className="login-submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
